package com.example.demo.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import sun.net.ftp.FtpProtocolException;

import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 从内蒙服务器下载文件到北京服务器
 * Created by rex on 2017/7/13.
 */
public class FtpDownload {
    private static Logger logger = Logger.getLogger(FtpDownload.class);

    /**
     * ftp上传
     * @param url
     * @param port
     * @param username
     * @param password
     * @param path
     * @param filename
     * @param input
     * @return
     */
    public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(url, port);//连接FTP服务器
            //如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.changeWorkingDirectory(path);
            ftp.storeFile(filename, input);

            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }


    public static boolean downFile(
            String url, //FTP服务器hostname
            int port,//FTP服务器端口
            String username, //FTP登录账号
            String password, //FTP登录密码
            //String remotePath,//FTP服务器上的相对路径
            String field,
            String date,
            String fanid,
            String[] keys,//要下载的文件名
            String localPathoot//下载后保存到本地的路径

    ) {
        FTPClient ftpClient = null;
        boolean success = false;

        try {
            ftpClient = new FTPClient();

            ftpClient.connect(url, port);// 连接FTP服务器
            ftpClient.login(username, password);// 登陆FTP服务器
            ftpClient.setControlEncoding("gb2312"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置文件格式
            ftpClient.enterLocalPassiveMode();
            logger.info(ftpClient.getReplyCode());
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.warn("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                //logger.info("FTP连接成功。");
            }
            //拼接字符创应该想到用StringBuilder
            String remotePath = "CMSFTPServer"+File.separator+field+File.separator+date+File.separator+fanid;
            ftpClient.changeWorkingDirectory(remotePath);
            FTPFile[] fs = ftpClient.listFiles();
            String localPath = localPathoot + File.separator + remotePath;
            File file = new File(localPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            for (FTPFile ff : fs) {
               // System.out.println(ff.getName());

                if (ff.getName().contains(keys[0]) && ff.getName().contains(keys[1])) {
                    logger.info("get it! "+ ff.getName());

                    File localFile = new File(localPath + "/" + ff.getName());
                    if (localFile.exists()) {
                        continue;
                    }
                    OutputStream os = new FileOutputStream(localFile);
                    long time1 = System.currentTimeMillis();
                    boolean b = ftpClient.retrieveFile(new String(ff.getName().getBytes("gb2312"), "ISO8859-1"), os);
                    long time2 = System.currentTimeMillis();
                    System.out.println("一个文件时间：" + (time2 - time1));

                    //System.out.println();
                    os.flush();
                    os.close();
                }
            }
            ftpClient.logout();
            success = true;
        } catch (SocketException e) {
            e.printStackTrace();
            logger.warn("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.warn("FTP的端口错误,请正确配置。");
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    public static void main(String[] args) throws IOException {
    //    downFile("10.144.136.104",21,"cms","chder@123","KULUN","20170715","FJ038",new String[]{"发电机","20170715131522"},"/var/alldata");
        //File file = new File("/var/alldata/data/CMSFTPServer/KULUN/20170713/FJ021/华电内蒙古库伦风电场_021_主轴承_前_径向_12800_加速度_0RPM_20170713230650.txt");
        //InputStream is = new FileInputStream(file);
        //uploadFile("10.144.136.104", 21, "cms", "chder@123", "CMSFTPServer/KULUN/20170712/FJ021", "test.txt", is);
//        String s = "1234567890";
//        System.out.println(s.substring(2));
    }
}
